package com.lib.common.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.SystemClock;
import androidx.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.lib.common.R;
import com.lib.utils.ConvertUtils;
import com.lib.utils.XLog;


public class GIFView extends View {
    /**
     * 默认为1秒
     */
    private static final int DEFAULT_GIF_DURATION = 1000;

    public static final int FIT_NONE = 0x0;
    public static final int FIT_X = 0x1;
    public static final int FIT_Y = 0x2;
    public static final int FIT_XY = 0x3;
    private Movie mGIF;
    private long mGIFStart;
    private int mCurrentFrame = 0;
    private int mScaleFit = FIT_NONE;
    private float mScaleW = 1f;
    private float mScaleH = 1f;
    private boolean mVisible = true;
    private boolean mRepeatForever = true;
    private boolean mCanTouchPause = false;
    private volatile boolean mPaused = false;
    private Paint mTrianglePaint = new Paint();
    // private RectF mRectF1;
    // private RectF mRectF2;
    private Path mTrianglePath;

    public GIFView(Context context) {
        this(context, null);
    }

    public GIFView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public GIFView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        mTrianglePaint.setColor(getContext().getResources().getColor(R.color.theme_color));
        mTrianglePaint.setAntiAlias(true);
        mTrianglePaint.setStrokeWidth(4);

        if (Build.VERSION.SDK_INT >= 11) {
            setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        }
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.GIFView, 0, 0);
        int gifResId = ta.getResourceId(R.styleable.GIFView_gif, -1);
        mScaleFit = ta.getInt(R.styleable.GIFView_scaleFit, mScaleFit);
        mCanTouchPause = ta.getBoolean(R.styleable.GIFView_canTouchPause, mCanTouchPause);
        mRepeatForever = ta.getBoolean(R.styleable.GIFView_repeat_forever, mRepeatForever);
        mPaused = ta.getBoolean(R.styleable.GIFView_paused, mPaused);
        ta.recycle();
        if (gifResId != -1) {
            mGIF = Movie.decodeStream(getResources().openRawResource(gifResId));
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            if (mGIF != null) {
                widthSize = mGIF.width();
            } else {
                widthSize = getSuggestedMinimumWidth();
            }
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            if (mGIF != null) {
                heightSize = mGIF.height();
            } else {
                heightSize = getSuggestedMinimumHeight();
            }
        }
        if (mGIF != null) {
            mScaleW = widthSize / ((float) mGIF.width());
            mScaleH = heightSize / ((float) mGIF.height());
        }
        setMeasuredDimension(widthSize, heightSize);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        if (mGIF != null) {
            if (!mPaused) {
                updateAnimationTime();
                drawMovieFrame(canvas);
                invalidateView();
            } else {
                drawMovieFrame(canvas);
                // 画暂停图标
                // if (mRectF1 == null) {
                // 	mRectF1 = new RectF(canvas.getWidth() / 2f - 20, canvas.getHeight() / 2f - 20, canvas
                // 		.getWidth() / 2f - 10, canvas.getHeight() / 2f + 20);
                // }
                // if (mRectF2 == null)
                // 	mRectF2 = new RectF(canvas.getWidth() / 2f + 10, canvas.getHeight() / 2f - 20, canvas
                // 		.getWidth() / 2f + 20, canvas.getHeight() / 2f + 20);
                // canvas.drawRect(mRectF1, mTrianglePaint);
                // canvas.drawRect(mRectF2, mTrianglePaint);
                // 画播放图标
                int width = getMeasuredWidth();//canvas.getWidth();
                int height = getMeasuredHeight();//canvas.getHeight();
                // int i = width / 10;
                int w = ConvertUtils.px2dp(XLog.sContext, 30);
                int w1 = ConvertUtils.px2dp(XLog.sContext, 15);
                if (mTrianglePath == null) {
                    mTrianglePath = new Path();
                    mTrianglePath.moveTo(width / 2f - w1, height / 2f - w);// 左上点
                    mTrianglePath.lineTo(width / 2f + w, height / 2f);    // 右点
                    mTrianglePath.lineTo(width / 2f - w1, height / 2f + w); // 左下点
                    mTrianglePath.close(); // 使这些点构成封闭的多边形
                }
                // mTrianglePaint.setColor(getContext().getResources().getColor(R.color.theme_color));
                mTrianglePaint.setStyle(Paint.Style.FILL);
                canvas.drawPath(mTrianglePath, mTrianglePaint);
                // 画外圆
                mTrianglePaint.setStyle(Paint.Style.STROKE);
                canvas.drawCircle(width / 2f, height / 2f, w * 2, mTrianglePaint);

                // mTrianglePaint.setStyle(Paint.Style.FILL);
                // mTrianglePaint.setColor(0xFF000000);
                // canvas.drawCircle(width / 2f, height / 2f, 2, mTrianglePaint);
                //
                // mTrianglePaint.setStrokeWidth(1);
                // canvas.drawLine(0, 0, getMeasuredWidth(), getMeasuredHeight(), mTrianglePaint);
                // canvas.drawLine(getMeasuredWidth(), 0, 0, getMeasuredHeight(), mTrianglePaint);
            }
        }
    }

    private void updateAnimationTime() {

        long now = SystemClock.uptimeMillis();
        // 如果第一帧，记录起始时间
        if (mGIFStart == 0) {
            mGIFStart = now;
        }
        // 取出动画的时长
        int duration = mGIF.duration();
        if (duration == 0) {
            duration = DEFAULT_GIF_DURATION;
        }
        // 算出需要显示第几帧
        if (now - mGIFStart >= duration && !mRepeatForever) {
            mPaused = true;
        }
        mCurrentFrame = (int) ((now - mGIFStart) % duration);
    }

    private void drawMovieFrame(Canvas canvas) {
        // 设置要显示的帧，绘制即可
        mGIF.setTime(mCurrentFrame);
        canvas.save();
        switch (mScaleFit) {
            case FIT_X:
                canvas.scale(mScaleW, 1);
                mGIF.draw(canvas, 0, (getMeasuredHeight() - mGIF.height()) / 2f);
                break;
            case FIT_Y:
                canvas.scale(1, mScaleH);
                mGIF.draw(canvas, (getMeasuredWidth() - mGIF.width()) / 2f, 0);
                break;
            case FIT_XY:
                canvas.scale(mScaleW, mScaleH);
                mGIF.draw(canvas, 0, 0);
                break;
            default:
                mGIF.draw(canvas, (getMeasuredWidth() - mGIF.width()) / 2f, (getMeasuredHeight() - mGIF.height()) / 2f);
                break;
        }
        canvas.restore();
    }

    @Override
    public void onScreenStateChanged(int screenState) {

        super.onScreenStateChanged(screenState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            mVisible = screenState == SCREEN_STATE_ON;
        }
        invalidateView();
    }

    @Override
    protected void onVisibilityChanged(@NonNull View changedView, int visibility) {

        super.onVisibilityChanged(changedView, visibility);
        mVisible = visibility == View.VISIBLE;
        invalidateView();
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {

        super.onWindowVisibilityChanged(visibility);
        mVisible = visibility == View.VISIBLE;
        invalidateView();
    }

    private void invalidateView() {

        if (mVisible) {
            if (Build.VERSION.SDK_INT >= 16) {
                postInvalidateOnAnimation();
            } else {
                invalidate();
            }
        }
    }

    /**
     * @param movieResId 设置gif图资源id
     */
    public void setGifResId(int movieResId) {

        mGIF = Movie.decodeStream(getResources().openRawResource(movieResId));
        requestLayout();
    }

    public void setGIF(Movie movie) {

        mGIF = movie;
        requestLayout();
    }

    public Movie getGIF() {

        return mGIF;
    }

    public void setGifFrameByTime(int time) {

        mCurrentFrame = time;
        invalidate();
    }

    /**
     * @param paused 设置暂停
     */
    public void setPaused(boolean paused) {

        mPaused = paused;
        if (!paused) {
            XLog.i("开始播放");
            mGIFStart = SystemClock.uptimeMillis() - mCurrentFrame;
        }
        invalidate();
    }

    /**
     * 判断gif图是否停止了
     *
     * @return true 已停止
     */
    public boolean isPaused() {

        return mPaused;
    }

    /**
     * @param canTouchPause 设置暂停
     */
    public void setCanTouchPause(boolean canTouchPause) {

        mCanTouchPause = canTouchPause;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (mCanTouchPause) {
                    setPaused(!mPaused);
                }
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDetachedFromWindow() {

        super.onDetachedFromWindow();
        setPaused(true);
    }
}